<template>
  <div class="box">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <div class="empty" v-if="shopList.length < 1">
        <p>购物车空空如也</p>
        <van-button type="info" size="mini" @click="$router.push('/goods/list')">去逛逛</van-button>
      </div>
      <div style="min-height:200px">
        <van-card
          v-for="(item, index) in shopListNew"
          :key="item.id"
          :num="shopList[index].count"
          :price="item.sell_price"
          :title="item.title"
          :thumb="item.thumb_path"
        >
          <div slot="footer">
            <van-stepper
              v-model="shopList[index].count"
              @change="changeNum"
              @plus="$store.commit('changeNum', 1)"
              @minus="$store.commit('changeNum', -1)"
            />
          </div>
        </van-card>
      </div>
      <van-submit-bar :price="sum" button-text="提交订单" @submit="onSubmit" />
    </van-pull-refresh>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
export default {
  data() {
    return {
      isLoading: false,
      //  商品列表数组
      shopList: [],
      //   所有商品的id数组
      shopIdList: [],
      idStr: 0,
      shopListNew: []
    }
  },
  created() {
    this.getshopData()
    this.changeNum()
  },
  computed: {
    //   计算总价
    sum() {
      let num = 0
      this.shopList.forEach(item => {
        num += item.price * item.count
      })
      // console.log(this.shopList);

      return num * 100
    }
  },
  methods: {
    onRefresh() {
      setTimeout(() => {
        this.$toast('刷新成功')
        this.isLoading = false
        this.count++
      }, 500)
    },
    // 根据id获取购物车列表数据
    async getshopcarList() {
      const { data: res } = await this.$http.get('/api/goods/getshopcarlist/' + this.idStr)
      //   console.log(res)
      if (res.status !== 0) {
        return this.$toast('获取商品列表信息失败')
      }
      this.shopListNew = res.message
      // console.log(this.shopListNew);
    },
    // 获取本地存储的数据
    getshopData() {
      // console.log(localStorage.getItem('list'));

      if (!localStorage.getItem('car')) return
      this.shopList = JSON.parse(localStorage.getItem('car'))
      //   遍历商品列表获取每个商品的id
      this.shopList.forEach(item => {
        this.shopIdList.push(item.id)
        this.idStr = this.shopIdList.join(',')
        this.getshopcarList()
      })
      console.log(this.shopList)
    },
    // 步进器修改数量
    changeNum() {
      // 进行同步本地中的商品的数量
      var jsonArr = JSON.stringify(this.shopList)
      localStorage.setItem('car', jsonArr)
      // 进行同步vuex中的数据
      var num = 0
      this.shopList.forEach(item => {
        num += item.count
      })
      // console.log(num);
      this.$store.commit('changeNum2', num)
    },
    onSubmit() {
      this.$toast.success('订单提交成功')
    }
  }
}
</script>
<style scoped>
.empty {
  padding: 15px 0;
  text-align: center;
}
.van-card__price {
  color: red !important;
}
</style>
